package com.brainardphotography.blog.utils;

import static java.lang.System.out;

import java.util.UUID;

import com.brainardphotography.blog.BlogEntry;

public class BlogEntryUtil {
	public static final String ILLEGAL_TITLE_CHARS = "[^A-Za-z0-9\\- ]";

	public String createEntryIdFromTitle(BlogEntry entry) {
		return createEntryIdFromTitle(entry.getTitle());
	}

	/**
	 * Returns a valid ID string based on the passed in title value. If the
	 * title is blank (null or whitespace), a UUID string will be generated for
	 * use as the ID.
	 * 
	 * @param title
	 *            Blog Entry title.
	 * @return Valid ID to use. This is not checked against the database for
	 *         uniqueness.
	 */
	public static final String createEntryIdFromTitle(String title) {
		String id = null;
		if (isBlank(title)) {
			id = UUID.randomUUID().toString();
		} else {
			id = title.replaceAll(ILLEGAL_TITLE_CHARS, "").trim()
					.replaceAll(" ", "-").toLowerCase();
		}

		return id;
	}

	public static final boolean isBlank(String string) {
		return string == null || "".equals(string.trim());
	}

	public static void main(String[] args) {
		System.out.println("Illegal Characters: " + ILLEGAL_TITLE_CHARS);
		String[] titles = new String[] { "   ", "\r\n", "", null,
				"Welcome to my blog!", "Welcome to my blog....",
				"This is the cat's meow. :)",
				"    blog entrh *()*($&%(!&*)\r\n*U$!    *(&$%" };

		for (String title : titles) {
			out.println(createEntryIdFromTitle(title));
		}
	}
}
